package cn.buk.qms.web;

import cn.buk.common.JsonResult;
import cn.buk.common.dto.CommonDto;
import cn.buk.common.sc.CommonSearchCriteria;
import cn.buk.tms.dao.PaymentOrderDao;
import cn.buk.tms.dto.PaymentOrderDto;
import cn.buk.tms.entity.misc.PaymentOrder;
import cn.buk.tms.entity.misc.User;
import cn.buk.qms.service.UserService;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import jakarta.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 *
 * @author yfdai
 * @date 2017-01-07
 */
@RestController
public class PaymentController extends BaseController {

  private static final Logger logger = LogManager.getLogger(PaymentController.class);

  private static final String TRADE_CLOSED = "TRADE_CLOSED";
  private static final String TRADE_SUCCESS = "TRADE_SUCCESS";
  private static final String TRADE_FINISHED = "TRADE_FINISHED";




  @Value("${owner_enterprise_id}")
  private int ownerId;

  @Override
  @InitBinder("sc")
  public void initBinder1(WebDataBinder binder) {
    binder.setFieldDefaultPrefix("sc.");
  }

  @Autowired
  private UserService userService;

  @Autowired
  private PaymentOrderDao paymentOrderDao;


  @RequestMapping("/alipayReturnUrl.do")
  public String returnUrl(HttpServletRequest request) {
    logger.info("returnURL");

    //获取支付宝GET过来反馈信息
    Map<String, String> params = new HashMap<>(10);
    Map<String, String[]> requestParams = request.getParameterMap();
    for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
      String name = iter.next();
      String[] values = requestParams.get(name);
      String valueStr = "";
      for (int i = 0; i < values.length; i++) {
        valueStr = (i == values.length - 1) ? valueStr + values[i]
            : valueStr + values[i] + ",";
      }
      //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
      valueStr = new String(valueStr.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
      params.put(name, valueStr);
      logger.info("returnURL__" + name + ": " + valueStr);
    }

    //计算得出通知验证结果
    boolean verifyResult = false;//AlipayNotify.verify(params);

    if (!verifyResult) {
      logger.warn("To verify the message from alipay failed.");
    }

    verifyResult = true;

    //商户订单号
    String outTradeNo = params.get("out_trade_no");

    //支付宝交易号
    String tradeNo = params.get("trade_no");

    //交易状态
    String tradeStatus = params.get("trade_status");

    //买家支付宝账号
    String buyerEmail = params.get("buyer_email");

    //买家支付宝ID
    String buyerId = params.get("buyer_id");

    if (verifyResult && tradeStatus != null) {//验证成功
      logger.info("returnURL: " + tradeStatus);

      if (TRADE_FINISHED.equals(tradeStatus) || TRADE_SUCCESS.equals(tradeStatus)) {
        PaymentOrder result = paymentOrderDao
            .updatePaymentOrderDone(outTradeNo, PaymentOrder.PAYMENT_ORDER_SUCCESS, tradeNo,
                buyerEmail, buyerId);
        if (result != null && result.getStatus() == PaymentOrder.PAYMENT_ORDER_SUCCESS) {
          return "success";
        } else {
          return "success, but order process failed.";
        }
      } else {
        return "trade status is ignored!";
      }
    } else {
      return "verified failed.";
    }
  }

  @RequestMapping("/alipayNotifyUrl.do")
  public String notifyUrl(HttpServletRequest request) {
    logger.info("notifyUrl");

    JsonResult jsonResult = new JsonResult();
    //获取支付宝POST过来反馈信息
    Map<String, String> params = new HashMap<>(10);
    Map<String, String[]> requestParams = request.getParameterMap();
    for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
      String name = iter.next();
      String[] values = requestParams.get(name);
      String valueStr = "";
      for (int i = 0; i < values.length; i++) {
        valueStr = (i == values.length - 1) ? valueStr + values[i]
            : valueStr + values[i] + ",";
      }
      //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
      //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "UTF-8");
      params.put(name, valueStr);
      //logger.info(name + ": " + valueStr);
    }

    String output = "fail";

    /**
     * 修改订单状态
     * /**
     * 订单状态
     * 0-待付款
     * 1-（担保模式）已付款，待发货
     * 2-（担保模式）已发货，待确认
     * 3-(即时到帐模式)已付款，待发货
     * 4-交易取消
     * 9-交易结束
     */
    boolean verifyResult = false; //AlipayNotify.verify(params);

    if (!verifyResult) {
      logger.info("To verify the message from alipay failed.");
    }

    verifyResult = true;

    //商户订单号
    String outTradeNo = params.get("out_trade_no");
    //支付宝交易号
    String tradeNo = params.get("trade_no");
    //交易状态
    String tradeStatus = params.get("trade_status");
    //买家支付宝账号
    String buyerEmail = params.get("buyer_email");
    //买家支付宝ID
    String buyerId = params.get("buyer_id");

    if (verifyResult && tradeStatus != null) {//验证成功
      //自己的业务代码
      logger.info("notifyURL: " + tradeStatus);
      if (TRADE_FINISHED.equals(tradeStatus) || TRADE_SUCCESS.equals(tradeStatus)) {
        //该判断表示买家已经确认收货，这笔交易完成
        logger.info(outTradeNo);
        PaymentOrder result = paymentOrderDao
            .updatePaymentOrderDone(outTradeNo, PaymentOrder.PAYMENT_ORDER_SUCCESS, tradeNo,
                buyerEmail, buyerId);
        if (result != null && result.getStatus() == PaymentOrder.PAYMENT_ORDER_SUCCESS) {
          output = "success";
          logger.info(output);
          jsonResult.setStatus("OK");
          jsonResult.setDesc(output);
        } else {
          logger.info("PaymentOrder result is null.");
        }

      } else if (TRADE_CLOSED.equals(tradeStatus)) {
        //该判断表示已取消这笔交易
        PaymentOrder result = paymentOrderDao
            .updatePaymentOrderDone(outTradeNo, PaymentOrder.PAYMENT_ORDER_CANCELED, tradeNo,
                buyerEmail, buyerId);
        if (result != null && result.getStatus() == PaymentOrder.PAYMENT_ORDER_CANCELED) {
//				if (paymentService.setProductOrderStatus(out_trade_no, PaymentOrder.PAYMENT_ORDER_CANCELED, trade_no, buyer_email, buyer_id)) {
          output = "success";
          jsonResult.setStatus("OK");
          jsonResult.setDesc(output);
        }
      } else {
        output = "success";
        jsonResult.setStatus("OK");
        jsonResult.setDesc(output);
      }
    }

    return "success";
  }

  @RequestMapping("/paymentOrders")
  public CommonDto<PaymentOrderDto> searchPaymentOrders(HttpServletRequest request,
      @ModelAttribute("sc") CommonSearchCriteria sc) {
    final int enterpriseId = getEnterpriseId(request);

    List<PaymentOrder> orders = paymentOrderDao.searchPaymentOrder(enterpriseId, 0, sc);
    List<PaymentOrderDto> dtos = new ArrayList<>();
    for (PaymentOrder order : orders) {
      PaymentOrderDto dto = new PaymentOrderDto();
      dtos.add(dto);

      BeanUtils.copyProperties(order, dto);

      User user = userService.getUserById(dto.getEnterpriseId());
      if (user != null) {
        dto.setEnterpriseName(user.getUsername());
      }
    }

    CommonDto<PaymentOrderDto> commonDto = new CommonDto<>();
    commonDto.setPage(sc.getPage());
    commonDto.setDataList(dtos);

    return commonDto;
  }
}
